import datetime
from django.http import HttpRequest, HttpResponse
from django.shortcuts import redirect, render
from MyBlog12 import models
import math


def addtest(request):
    i = 1
    while i < 100:
        c = models.Content()
        c.creation_time = datetime.datetime.now()
        c.title = str(i) + '条数据的标题'
        c.text = str(i) + '条数据的内容'
        c.category_id = 1
        c.save()
        i += 1
    return 'ok'


def list(request, id=0):
    #问题1：怎么上取整？    -> 算总页面
    #问题2：怎么用orm工具取数据库中间的数据 -> 取分页数据   arr[3:10]，数组分片
    #问题3：怎么取数据库某表有多少数据  -> 算总页数  count()取数据条数\
    key = request.GET.get('key')
    if key == None:
        key = ''
    leibie = models.Category.objects.all()

    contents = models.Content.objects
    if id != '0':
        contents = contents.filter(category_id=id)
    if key != '':
        contents = contents.filter(title__contains=key)
    total = contents.count()
    page = request.GET.get('page')
    if page == None or page == '':
        page = '1'
    try:
        page = int(page)
    except:
        page = 1
    if (page < 1):
        page = 1
    start = (page - 1) * 10
    end = page * 10
    totalPage = math.ceil(total / 10)
    liebiao = contents.order_by("-creation_time")[start:end]
    context = {
        "leibie": leibie,
        "liebiao": liebiao,
        "total_page": totalPage,
        "current_page": page,
        "next_page": page + 1,
        "total_count": total
    }
    return render(request, "list.html", context)

start_day = datetime.datetime(2021,11,22)

# 1.从数据库读取详细信息，并展示  查询数据库  做过  #传一个文章对象给界面
# 2.浏览次数应该+1      更新数据库  无需传数据给界面
# 3.相关推荐：考虑读取有重复tag的文章   查询数据库，列表    #传一个文章列表给界面
# 4.发布评论的html（ajax提交或提交后刷新页面）  添加    #界面传数据给后台入库，并且界面要重新更新评论列表
# 5.评论列表（分页?page=??）  查询    #传个评论列表给界面显示
def show(request, id):
    page = request.GET.get('page')
    if (page == None or page == ''):
        page = 1
    try:
        page = int(page)
    except:
        page = 1
    if (page < 1):
        page = 1
    ps = 5
    start = (page-1) * ps
    end = page * ps
    wenzhang = models.Content.objects.get(id=id)
    wenzhang.view_count += 1
    wenzhang.save()
    tag = wenzhang.tags.split(',')[0]
    tuijian = models.Content.objects.filter(tags__contains=tag)[0:8]
    pinglun = models.Comment.objects.filter(content_id=id).order_by('-creation_time')[start:end]
    c = models.Content.objects.count()
    context = {
        'wenzhang':wenzhang,
        'pinglun':pinglun,
        'tuijian':tuijian,
        'current_page':page,
        'total_page': math.ceil(models.Comment.objects.filter(content_id=id).count() /  ps),
        'count':c,
        'days': (datetime.datetime.now() - start_day).days
    }
    return render(request,'show.html',context)

def addcomment(request):
    c = models.Comment()
    c.text = request.POST['content']
    c.creation_time = datetime.datetime.now()
    c.mail = request.POST['mail']
    c.name = request.POST['nickname']
    c.like = 0
    c.dislike = 0
    c.ip = get_ip(request)
    c.content = models.Content.objects.get(id = request.POST['id'])
    c.save()
    return redirect('/show/'+request.POST['id']+'#comment_list')

#X-Forwarded-For:简称XFF头，它代表客户端，也就是HTTP的请求端真实的IP，只有在通过了HTTP 代理或者负载均衡服务器时才会添加该项。
def get_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]#所以这里是真实的ip
    else:
        ip = request.META.get('REMOTE_ADDR')#这里获得代理ip
    return ip












#后台管理部分
def login(request):
    dict = {}
    if request.POST.get('account') and request.POST.get('password'):
        uname = request.POST.get('account')
        u = models.User.objects.filter(username=uname)
        if len(u) == 0:
            dict['msg']='用户不存在'
        else:
            if u[0].password != request.POST.get('password'):   #密码应该加密存储
                dict['msg']='密码错误'
            else:
                request.session['userId'] = u[0].id
                return redirect('/frame')
        return render(request,'login.html',dict)
    else:
        return render(request,'login.html',dict)

def frame(request):
    if request.session.get('userId') ==None:    #判断是否登录
        return redirect('/login')
    return render(request,'frame.html')
